<template>
    <div>
      <el-card class="box-card">
        <h2>调度申请</h2>
        <el-form :model="applicationForm" :rules="rules" ref="applicationForm" label-width="120px">
          <el-form-item label="申请标题：" prop="title">
            <el-input v-model="applicationForm.title" clearable></el-input>
          </el-form-item>
          <el-form-item label="调度任务：" prop="task">
            <el-select v-model="applicationForm.task" placeholder="请选择调度任务">
              <el-option
                v-for="task in tasks"
                :key="task"
                :label="task"
                :value="task"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="创建日期：" prop="beginTime">
            <el-date-picker
              v-model="applicationForm.beginTime"
              type="date"
              placeholder="选择创建日期"
              :disabled-date="beginDatePickerOptions"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="提交日期：" prop="endTime">
            <el-date-picker
              v-model="applicationForm.endTime"
              type="date"
              placeholder="选择提交日期"
              :disabled-date="endDatePickerOptions"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="申请描述：" prop="description">
            <el-input v-model="applicationForm.description" type="textarea" :autosize="{ minRows: 1, maxRows: 2 }"></el-input>
          </el-form-item>
          <el-form-item label="申请内容：" prop="content">
            <el-input v-model="applicationForm.content" type="textarea" :autosize="{ minRows: 8, maxRows: 11 }"></el-input>
          </el-form-item>
          <el-form-item label="申请附件：">
            <el-upload
              action="https://apifoxmock.com/m1/4767131-4420546-default/api/application_upload"
              list-type="text"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
            >
              <el-button type="warning">上传附件</el-button>
              <div class="el-upload__tip" style="margin-left: 5px;">上传申请附件，单个文件最大2MB</div>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="warning" @click="submitForm('submit')">提交</el-button>
            <el-button type="warning" @click="submitForm('draft')">保存为草稿</el-button>
            <el-button style="margin-left: 320px;" @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </template>

<script>
export default {
  props: {
    info: {
      type: String,
      default: ''
    }
  },
  data() {
    const validateBeginTime = (rule, value, callback) => {
            if (value === "" || value === null) {
                callback(new Error("请选择创建日期"));
            } else {
                if (this.applicationForm.endTime !== "") {
                    this.$refs.applicationForm.validateField("endTime");
                }
                callback();
            }
        };
      return {
          applicationForm: {
              title: '',
              task: '',
              beginTime: '',
              endTime: '',
              description: '', // 添加描述字段
              content: '',
              attachments: []
          },
          tasks: [], // Array to hold task data
          rules: {
              title: [{ required: true, message: '请输入申请标题', trigger: 'blur' }],
              task: [{ required: true, message: '请选择调度任务', trigger: 'change' }],
              beginTime: [
                  { required: true, validator: validateBeginTime, trigger: 'change' },
                  // { validator: this.validateBeginTime, trigger: 'change' }
              ],
              endTime: [
                  { required: true, message: '请选择提交日期', trigger: 'change' },
                  { validator: this.validateEndTime, trigger: 'change' }
              ],
              content: [{ required: true, message: '请输入申请内容', trigger: 'blur' }],
              description: [{ required: true, message: '请输入简单描述内容', trigger: 'blur' }]
          },
          hasInfo: false,
          initBeginTime: ''
    }
  },
  methods: {
    beginDatePickerOptions(time) {
      if(!this.hasInfo) {
        return time.getTime() < Date.now() - 86400000
      } else {
        return true
      }
    },
    endDatePickerOptions(time) {
      if(this.applicationForm.beginTime) {
        return time.getTime() < new Date(this.applicationForm.beginTime).getTime()
      } else {
        return false
      }
    },
    handleUploadSuccess(response, file) {
      this.applicationForm.attachments.push(response.url)
      console.log(response.rul)
      this.$message.success(`${file.name} 上传成功`)
    },
    handleUploadError(err, file) {
      this.$message.error(`${file.name} 上传失败`)
    },
    submitForm(status) {
      this.$refs.applicationForm.validate(valid => {
        if (valid) {
          this.axios({
            url: "https://apifoxmock.com/m1/4767131-4420546-default/api/application_draft",               // 请求地址
            method: "post",                       // 请求方法
            headers: {                            // 请求头
              "Content-Type": "application/json",
            },
            params: {                             // 请求参数
              title:this.applicationForm.title,
              task:this.applicationForm.task,
              beginTime:this.applicationForm.beginTime,
              endTime:this.applicationForm.endTime,
              description:this.applicationForm.description,
              content:this.applicationForm.content,
              status:status
            },
          })
          .then(() => {
            if(status === 'submit') {
              this.$message.success('申请提交成功')
            } else if(status === 'draft') {
              this.$message.success('草稿保存成功')
            }
            console.log(this.info)
            this.hasInfo = false
            this.resetForm()
          })
          .catch(error => {
            console.error('Error creating application:', error)
            this.$message.error('申请起草失败')
          })
        } else {
          this.$message.error('请完善表单信息')
        }
      })
    },
    resetForm() {
      this.$refs.applicationForm.resetFields()
      this.applicationForm.attachments = []
      if(this.info !== '') {
        this.applicationForm.beginTime = this.initBeginTime
      }
    },
    validateBeginTime(rule, value, callback) {
      if (!this.hasInfo && value && new Date(value).getTime() < Date.now() - 86400000) {
        callback(new Error('创建日期不能早于今天'))
      } else {
        callback();
      }
    },
    validateEndTime(rule, value, callback) {
      if (value && new Date(value).getTime() < new Date(this.applicationForm.beginTime).getTime()) {
        callback(new Error('提交日期不能早于创建日期'))
      } else {
        callback()
      }
    },
    fetchTasks() {
      this.axios.get('https://apifoxmock.com/m1/4767131-4420546-default/api/get_tasks',
        {params: {email: sessionStorage.getItem('userInfo')}})
      .then(response => {
        this.tasks = response.data.task
      })
      .catch(error => {
        console.error('Error fetching tasks:', error)
        this.$message.error('获取调度任务列表失败')
      });
    },
    initializeForm() {
      console.log(this.info)
      this.axios.get(`https://apifoxmock.com/m1/4767131-4420546-default/api/get_application_draft`,///${info}
      {params: {title:this.info}})
      .then(response => {
        // 将返回的数据填充到表单中
        this.applicationForm.title = response.data.title
        this.applicationForm.task = response.data.task
        this.applicationForm.beginTime = response.data.beginTime
        this.applicationForm.endTime = response.data.endTime
        this.applicationForm.description = response.data.description
        this.applicationForm.content = response.data.content

        this.initBeginTime = response.data.beginTime
      })
      .catch(error => {
        console.error('Failed to fetch data:', error)
        // 处理请求失败的情况
      })
    },
  },
  created() {
    this.fetchTasks()
    if(this.info !== ''){
      this.hasInfo = true
      this.initializeForm()
      this.$emit('clearInfo')
    }
  },
};
</script>

<style scoped>
.box-card {
  height:100vh;
}
.el-form-item {
  margin-bottom: 20px;
}
</style>
